<template>
    <van-nav-bar title="产品详情" left-text="" left-arrow @click-left="goBack" @click-right="showShare = true">
        <template #right>
            <van-icon name="ellipsis" size="18" />
        </template>
    </van-nav-bar>

    <!-- 产品图 -->
    <van-swipe :autoplay="3000" lazy-render>
        <van-swipe-item v-for="item in detail.thumbs_list">
            <img :src="item" height="270" fit="cover" />
        </van-swipe-item>
    </van-swipe>

    <div class="detailbox">
        <h4>{{ detail.name }}</h4>
        <div class="price" style="color: rgb(238, 10, 36);font-size: 22px;">
            <em>单独购买￥</em>{{ detail.price }} | <em>拼团价格￥</em> {{ detail.buy }}
            <em style="float: right; color: rgb(183, 183, 191);">库存 {{ detail.stock }} 件</em>
        </div>
    </div>
    <div class="allkbox"></div>

    <!-- 商品规格和服务 -->
    <div class="info_choice">
        <!-- Sku 商品规格 -->
        <div class="commodity" @click="SkuShow = true">
            <div class="opt">
                <div class="title wanl-gray">
                    选择
                </div>
                <div class="option">
                    <div class="selected">
                        <div>
                            <span>尺码</span>
                            <span>颜色</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wanl-gray" onclick="location.href = './sku.html' ">
                <img src="/assets/images/go.png">
            </div>
        </div>
        <!-- 服务 -->
        <div class="commodity" @click="showSheet = true">
            <div class="opt">
                <div class="title wanl-gray">
                    服务
                </div>
                <div class="option">
                    <div class="selected">
                        <div>
                            <span>7天无理由退款</span>
                            <span>·</span>
                            <span>24小时内发货</span>
                            <span>·</span>
                            <span>假一赔十</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wanl-gray" onclick="location.href = './server.html' ">
                <img src="/assets/images/go.png">
            </div>
        </div>
    </div>

    <!-- 商品详情和评价 -->
    <div class="detailbox_2">
        <van-tabs type="card" color="#ee0a24">
            <van-tab title="产品参数">
                <p v-html="detail.content"></p>
            </van-tab>
            <van-tab title="商品评价">
                <div class="rate">
                    <div class="rate-header" v-if="busRate != null">
                        <div class="rate-score">
                            <h4>{{ busRate.rate_text }}</h4>
                            <strong>{{ busRate.rate }}</strong>
                        </div>
                        <div class="rate-graph" v-for="(thumb, index) in busRate.thumbs_list" :key="index">
                            <van-field name="rate" label="" :rules="[{ required: true, message: '请选择评分' }]">
                                <template #input>
                                    <van-rate v-model="busRate.rate" icon="fire" void-icon="fire-o" readonly />
                                </template>
                            </van-field>
                        </div>
                    </div>
                    <div class="rate-content">
                        <div>
                            <div class="review-box" v-for="(orderpro, index) in orderproList" :key="index">
                                <div class="review-item">
                                    <div class="from-whom">
                                        <div class="avatar">
                                            <img :src="orderpro.business.avatar_text" alt="" />
                                        </div>
                                        <div class="name">{{ orderpro.business.nickname }}</div>
                                    </div>
                                    <div class="review-details">
                                        <div class="content" v-if="orderpro.comment != null">{{ orderpro.comment }}</div>
                                        <div class="content" v-else>暂无评价</div>
                                        <div v-if="orderpro.thumbs_list.length > 0">
                                            <img v-for="(thumb, index) in orderpro.thumbs_list" :key="index" :src="thumb" alt="">
                                        </div>
                                        <div v-else>暂无评论照片</div>
                                        <div class="time">2022-09-19 01:05:57</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-if="orderproList.length == 0 && busRate == null">
                            <div class="rate-empty">该商品还没有人写评价呢</div>
                        </div>
                    </div>
                </div>
            </van-tab>
        </van-tabs>
    </div>
    <div class="clear"></div>
    <div class="h54"></div>

    <!-- 商品SKU -->
    <van-sku v-model="SkuShow" ref="SkuRef" stepper-title="购买数量" :sku="sku" :goods="goods" :goods-id="proid"
        :properties="properties" @buy-clicked="buy" @add-cart="addCart">
        <!-- 自定义 sku actions -->
        <template #sku-actions="props">
            <div class="van-sku-actions">
                <van-button square size="large" type="warning" @click="props.skuEventBus.emit('sku:addCart')">
                    加入购物车
                </van-button>
                <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
                <van-button square size="large" type="danger" @click="props.skuEventBus.emit('sku:buy')">
                    单独购买
                </van-button>
                <van-button square size="large" type="danger" @click="teamJoin">
                    参与拼团
                </van-button>
                <van-button square size="large" type="danger" @click="teamAdd">
                    发起拼团
                </van-button>
            </div>
        </template>
    </van-sku>

    <!-- 底部操作按扭 -->
    <van-action-bar>
        <router-link to="/chat/index">
            <van-action-bar-icon icon="chat-o" text="客服" />
        </router-link>
        <van-action-bar-icon icon="cart-o" badge="12" text="购物车" @click="toPages" />
        <!-- star-o -->
        <van-action-bar-icon :icon="detail.collection" text="收藏" color="#ee0a24" @click="collect" />
        <van-action-bar-button type="danger" text="立即购买" @click="SkuShow = true" />
    </van-action-bar>


    <!-- 动作面板，协议内容 -->
    <van-action-sheet v-model:show="showSheet" title="协议内容">
        <div class="ProductTip">
            三、我们如何使用信息 <br />
            四、我们如何共享信息<br />
            五、我们如何转让信息<br />
            六、我们如何公开披露信息<br />
            七、一般储存期限<br />
            八、我们如何确保您的信息安全<br />
            九、您能做什么<br />
            十、我们如何处理未成年人的个人信息<br />
            十一、您的个人信息的存储地点<br />
            十二、本隐私权政策不适用的范围<br />
            十三、本隐私权政策如何更新<br />
            十四、联系我们<br />
        </div>
    </van-action-sheet>


    <!-- 分享面板 -->
    <van-share-sheet v-model:show="showShare" title="立即分享给好友" :options="sharelist" />

</template>

<script setup>
import VanSku from 'vant-sku';
import 'vant-sku/dist/index.css'
import cart from '../../api/cart';
import { reactive } from 'vue';

const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.go(-1) }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ?? {})
const proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0
const showShare = ref(false)
const showSheet = ref(false)
const detail = ref({})
const sharelist = ref([
    [
        { name: '微信', icon: 'wechat' },
        { name: '朋友圈', icon: 'wechat-moments' },
        { name: '微博', icon: 'weibo' },
        { name: 'QQ', icon: 'qq' },
    ],
    [
        { name: '复制链接', icon: 'link' },
        { name: '分享海报', icon: 'poster' },
        { name: '二维码', icon: 'qrcode' },
        { name: '小程序码', icon: 'weapp-qrcode' },
    ],
])

// sku属性
const SkuRef = ref(null)
const SkuShow = ref(false)
const sku = ref({})
const goods = ref({})
const properties = ref([])

// 评论
const busRate = ref({})
const orderproList = ref({})

// 获取商品详情
onBeforeMount(async () => {
    await getProductInfoData();
    getRateInfo();
})

// 获取商品详情
const getProductInfoData = async () => {
    let result = await Api.ProductInfo({
        proid: proid,
        busid: LoginUser.id ?? 0
    })
    if (result.code == 1) {
        let ProductData = result.data.info
        let SkuData = result.data.sku
        let PropertiesData = result.data.properties

        detail.value = ProductData
        sku.value = SkuData
        properties.value = Object.values(PropertiesData)
        goods.value = {
            picture: detail.value.thumbs_text
        }
    }
}

// 添加购物车
const addCart = async (SkuData) => {

    SkuShow.value = false;

    if (JSON.stringify(LoginUser) == '{}') {
        toast({
            message: '未登陆，请先去登陆',
            onClose: () => {
                proxy.$router.push('/business/login')
            }
        });

        return false;
    }

    //数量
    const selectedNum = SkuData.selectedNum

    if (selectedNum <= 0) {
        error('数量不能为小于0');
        return false
    }

    //判断是否有选择规格
    if (properties.value.length > 0 && !SkuData.selectedSkuComb) {
        error('请选择商品规格')
        return false;
    }

    let attrs = []

    if (properties.value.length > 0) {
        let properties = SkuData.selectedSkuComb.properties
        properties.forEach((item) => {
            if (item.v) {
                attrs.push(item.v[0].id)
            }

        })
    }

    let data = {
        busid: LoginUser.id,
        proid: proid,
        nums: selectedNum,
        attrs: attrs.toString()
    }
    let result = await Api.CartAdd(data)
    if (result.code == 1) {
        getProductInfoData()
        success(result.msg);
    }
    else {
        error(result.msg);
    }

}

// 收藏商品
const collect = async () => {
    await getProductInfoData();
    // console.log(detail.value.collection);
    if (detail.value.collection == 'star-o') {
        let result = await Api.ProductCollect({
            busid: LoginUser.id,
            proid: proid
        });

        if (result.code == 1) {
            getProductInfoData();
            success(result.msg);
        } else {
            error(result.msg);
        };
    } else {
        let result = await Api.ProductCancelCollect({
            busid: LoginUser.id,
            proid: proid
        });

        if (result.code == 1) {
            getProductInfoData();
            success(result.msg);
        } else {
            error(result.msg);
        }
    }
}

const toPages = () => { proxy.$router.push('/product/cart') }

// 直接购买
const buy = async (SkuData) => {
    // 收起sku面板
    SkuShow.value = false;

    // 判断是否登录
    if (JSON.stringify(LoginUser) == '{}') {
        toast({
            message: '未登陆，请先去登陆',
            onClose: () => {
                proxy.$router.push('/business/login')
            }
        });

        return false;
    }

    //数量
    const selectedNum = SkuData.selectedNum

    if (selectedNum <= 0) {
        error('数量不能为小于0');
        return false
    }

    //判断是否有选择规格
    if (properties.value.length > 0 && !SkuData.selectedSkuComb) {
        error('请选择商品规格')
        return false;
    }

    let attrs = []

    if (properties.value.length > 0) {
        let properties = SkuData.selectedSkuComb.properties
        properties.forEach((item) => {
            if (item.v) {
                attrs.push(item.v[0].id)
            }

        })
    }

    let data = {
        busid: LoginUser.id,
        proid: proid,
        nums: selectedNum,
        attrs: attrs.toString(),
        isDirectlyBuy: 1
    }
    let result = await Api.CartAdd(data)
    console.log(result);
    let cartid = result.data.cartid;
    if (result.code == 1) {
        getProductInfoData()
        success(result.msg);
    }
    else {
        error(result.msg);
    }
    console.log(cartid);

    proxy.$router.push({
        path: '/product/confirm',
        query: {
            cartids: cartid,
            isDirectlyBuy: 1
        }
    })
}

// 获取评论列表
const getRateInfo = async () => {
    let result = await Api.RateInfo({
        busid: LoginUser.id,
        proid: proid,
    })

    if (result.code == 1) {
        busRate.value = result.data.busRate;
        orderproList.value = result.data.orderpro;
    } else {
        busRate.value = {};
        orderproList.value = [];
    }
}

// 发起拼团
const teamAdd = () =>
{
    SkuShow.value = false;

    if(JSON.stringify(LoginUser) == '{}')
    {
        toast({
            message: '未登陆，请先去登陆',
            onClose: () =>{
                proxy.$router.push('/business/login')
            }
        });

        return false;
    }

    // 通过 ref 可以获取到 Sku 实例并调用实例方法，详见组件实例方法。
    let SkuData = SkuRef.value.getSkuData()

    const selectedNum = SkuData.selectedNum

    if(selectedNum <= 0)
    {
        error('数量不能为小于0');
        return false
    }

    //判断是否有选择规格
    if(properties.value.length > 0 && !SkuData.selectedSkuComb)
    {
        error('请选择商品规格')
        return false;
    }

    let relationids = []

    if(properties.value.length > 0)
    {
        let  properties = SkuData.selectedSkuComb.properties
        properties.forEach((item) => {
            if(item.v)
            {
                var id = item.v[0] ? item.v[0].id : 0;
                relationids.push({
                    id: id,
                    name: item.v[0].name ?? '',
                    price: item.v[0].price
                })
            }
                
        })
    }

    // 存储属性数据
    proxy.$cookies.set('relationids', JSON.stringify(relationids))

    //路由跳转
    proxy.$router.push({
        path: '/team/add',
        query:{
            proid: proid,
            nums: selectedNum
        }
    })
}

// 参与拼团
const teamJoin = () =>
{
    SkuShow.value = false;

    if(JSON.stringify(LoginUser) == '{}') {
        toast({
            message: '未登陆，请先去登陆',
            onClose: () =>{
                proxy.$router.push('/business/login')
            }
        });

        return false;
    }

    // 通过 ref 可以获取到 Sku 实例并调用实例方法，详见组件实例方法。
    let SkuData = SkuRef.value.getSkuData()

    const selectedNum = SkuData.selectedNum

    if(selectedNum <= 0)
    {
        error('数量不能为小于0');
        return false
    }

    //判断是否有选择规格
    if(properties.value.length > 0 && !SkuData.selectedSkuComb)
    {
        error('请选择商品规格')
        return false;
    }

    let relationids = []

    if(properties.value.length > 0)
    {
        let  properties = SkuData.selectedSkuComb.properties
        properties.forEach((item) => {
            if(item.v)
            {
                var id = item.v[0] ? item.v[0].id : 0;
                relationids.push({
                    id: id,
                    name: item.v[0].name ?? '',
                    price: item.v[0].price
                })
            }
        })
    }

    // 存储属性数据
    proxy.$cookies.set('relationids', JSON.stringify(relationids))

    //路由跳转
    proxy.$router.push({
        path: '/team/add',
        query:{
            proid: proid,
            nums: selectedNum,
            isJoin: 1
        }
    })
}

</script>
<style>
.van-share-sheet__options {
    justify-content: center;
}

.van-tabs__nav--card {
    margin: 0;
}
</style>